import { loginAction } from "@/store/actions";
import { Card, Form, Input, Button, Checkbox, message } from "antd";
import { useDispatch } from "react-redux";
import { useHistory } from "react-router-dom";
import logo from "@/assets/logo.png";
import "./index.scss";

//设置类型
type FormData = { mobile: string; code: string; remember: boolean };
  

const Login = () => {
  const history = useHistory();
  const dispatch =  useDispatch()

  const onFinish = async (values: FormData) => {
    console.log("Success:", values);

    //解构出mobile和code
    const { mobile, code } = values;
       
    await dispatch(loginAction(mobile,code))
         
    //提示用户登录成功
    message.success("登录成功");
    //跳转到首页
    history.push("/home");
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };

  return (
    <div className="login">
      {/* 卡片  */}
      <Card className="login-container">
        {/* logo */}
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 24 }}
          initialValues={{
            remember: true,
            mobile: "13911111111",
            code: "246810",
          }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
          // 表单触发输入框焦点
          validateTrigger={["onChange", "onBlur"]}
        >
          <Form.Item
            name="mobile"
            rules={[
              { required: true, message: "手机号不能为空!" },
              {
                pattern:
                  /^(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
                message: "手机格式有误！",
              },
            ]}
          >
            <Input size="large" />
          </Form.Item>

          <Form.Item
            name="code"
            rules={[
              { required: true, message: "验证码不能为空!" },
              {
                pattern: /^\d{6}$/,
                message: "验证码格式有误！",
              },
            ]}
          >
            <Input size="large" />
          </Form.Item>

          <Form.Item
            name="remember"
            valuePropName="checked"
            wrapperCol={{ span: 24 }}
            rules={[
              {
                validator: (_, value) =>
                  value
                    ? Promise.resolve()
                    : Promise.reject(new Error("请勾选用户协议")),
              },
            ]}
          >
            <Checkbox>我已阅读并同意[隐私条款]和[用户协议]</Checkbox>
          </Form.Item>

          <Form.Item wrapperCol={{ span: 24 }}>
            <Button size="large" type="primary" block htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Login;
